package pers.lonestar.framework.utils.support.analysis.analyser;

import java.util.List;

import org.slf4j.Logger;

import pers.lonestar.framework.utils.support.contexts.XlsxReadContext;
import pers.lonestar.framework.utils.support.exception.ExcelAnalysisException;
import pers.lonestar.framework.utils.support.metadata.read.ReadSheet;
import pers.lonestar.framework.utils.support.metadata.read.ReadWorkbook;
import pers.lonestar.framework.utils.support.utils.FileUtil;

public class ExcelAnalyserImpl implements ExcelAnalyser {
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(ExcelAnalyserImpl.class);
    private final ExcelReadExecutor excelReadExecutor;
    private final XlsxReadContext analysisContext;

    public ExcelAnalyserImpl(XlsxReadContext analysisContext) {
        this.analysisContext = analysisContext;
        this.excelReadExecutor = new XlsxSaxAnalyser(analysisContext);
    }

    @Override
    public void analysis(List<ReadSheet> readSheetList) {
        if (readSheetList.isEmpty()) {
            throw new IllegalArgumentException("No sheets were provided");
        }
        analysisContext.setParameterSheetDataList(readSheetList);
        try {
            excelReadExecutor.execute();
        } catch (ExcelAnalysisException e) {
            finish();
            throw e;
        } catch (Exception e) {
            finish();
            throw new ExcelAnalysisException(e);
        }
    }

    @Override
    public void finish() {
        Exception exception = null;
        if (analysisContext == null) {
            return;
        }
        ReadWorkbook readWorkbook = analysisContext.getReadWorkbook();
        if (readWorkbook.getReadCache() != null) {
            try {
                readWorkbook.getReadCache().destroy();
            } catch (Exception e) {
                exception = e;
            }
        }
        if (readWorkbook.getOpcPackage() != null) {
            try {
                readWorkbook.getOpcPackage().revert();
            } catch (Exception e) {
                exception = e;
            }
        }
        if (readWorkbook.getInputStream() != null) {
            try {
                readWorkbook.getInputStream().close();
            } catch (Exception e) {
                exception = e;
            }
        }
        if (readWorkbook.getTmpFile() != null) {
            try {
                FileUtil.delete(readWorkbook.getTmpFile());
            } catch (Exception e) {
                exception = e;
            }
        }
        if (exception != null) {
            throw new ExcelAnalysisException("Can not finish analysis IO");
        }
        if (log.isDebugEnabled()) {
            log.debug("All analysis IO have been finished");
        }
    }
}
